import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'widges/course_card.dart'; // 导入CourseInfo模型
import 'models/ddl_item.dart'; // 导入DDLItem

/// 应用数据管理类，负责所有本地数据的统一读写和缓存
class AppDataManager {
  // 单例实现，保证全局只有一个实例
  static final AppDataManager _instance = AppDataManager._internal();
  factory AppDataManager() => _instance;
  AppDataManager._internal();

  // 当前日期数据
  DateTime _currentDate = DateTime.now();
  String _currentMonth = '';
  String _currentWeekDay = '';
  String _currentDay = '';
  bool _isLargeMonth = false;

  // 课表数据缓存
  List<CourseInfo> _courseTable = [];

  // 课表数据文件名
  static const String _courseTableFile = 'course_table.json';

  // DDL数据缓存
  List<DDLItem> _ddlList = [];
  List<DDLItem> _recycleBin = [];

  static const String _ddlFile = 'ddl_list.json';
  static const String _ddlRecycleFile = 'ddl_recycle.json';

  // DDL统计数据缓存
  Map<String, Map<String, int>> _ddlStats = {};

  // DDL统计数据文件名
  static const String _ddlStatsFile = 'ddl_stats.json';

  // 小目标数据缓存
  Map<String, Map<String, int>> _goalStats = {};

  // 小目标数据文件名
  static const String _goalStatsFile = 'goal_stats.json';

  // 自律值缓存
  Map<String, Map<String, int>> _disciplineScores = {};
  static const String _disciplineScoresFile = 'discipline_scores.json';

  /// 初始化，建议在App启动时调用
  /// 作用：加载本地存储的课表数据到内存
  Future<void> init() async {
    print('开始初始化数据...');
    await _loadCourseTable();
    await loadDDLList();
    await loadDDLRecycle();
    await _loadDDLStats(); // 加载统计数据
    await _loadGoalStats(); // 加载小目标数据
    await _loadDisciplineScores(); // 加载自律值数据
    updateDateData(); // 更新日期数据
    print('初始化完成，当前日期：$_currentDate');
    print('月份：$_currentMonth');
    print('星期：$_currentWeekDay');
    print('日期：$_currentDay');
    print('是否大月：$_isLargeMonth');
  }

  /// 更新日期数据
  void updateDateData() {
    _currentDate = DateTime.now();
    
    // 设置月份（中文）
    final monthNames = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    _currentMonth = '${monthNames[_currentDate.month - 1]}月';
    
    // 设置日期
    _currentDay = '${_currentDate.day}';
    
    // 设置星期几（中文）
    final weekDays = ['一', '二', '三', '四', '五', '六', '日'];
    _currentWeekDay = '星期${weekDays[_currentDate.weekday - 1]}';
    
    // 判断是否是大月
    _isLargeMonth = [1, 3, 5, 7, 8, 10, 12].contains(_currentDate.month);
  }

  /// 获取当前月份
  String get currentMonth => _currentMonth;

  /// 获取当前星期几
  String get currentWeekDay => _currentWeekDay;

  /// 获取当前日期
  String get currentDay => _currentDay;

  /// 判断是否是大月
  bool get isLargeMonth => _isLargeMonth;

  /// 获取课表数据（返回缓存，页面可直接用）
  List<CourseInfo> get courseTable => _courseTable;

  /// 获取未完成DDL（主页和备忘录用）
  List<DDLItem> get ddlList => _ddlList;

  /// 获取回收站DDL
  List<DDLItem> get recycleBin => _recycleBin;

  /// 加载课表数据（从本地文件读取）
  Future<void> _loadCourseTable() async {
    try {
      final file = await _getLocalFile('course_table.json');
      if (!await file.exists()) {
        _courseTable = [];
        return;
      }
      
      final contents = await file.readAsString();
      if (contents.isEmpty) {
        _courseTable = [];
        return;
      }
      
      final jsonData = jsonDecode(contents);
      if (jsonData is List) {
        _courseTable = List<Map<String, dynamic>>.from(jsonData)
            .map((e) => CourseInfo.fromJson(e))
            .toList();
      } else {
        _courseTable = [];
      }
    } catch (e) {
      print('加载课表数据失败: $e');
      _courseTable = [];
    }
  }

  /// 保存课表数据（写入本地文件）
  Future<void> saveCourseTable(List<Map<String, dynamic>> courses) async {
    try {
      print('保存课表数据...');
      print('课程数量: ${courses.length}');
      
      // 确保所有必要字段都存在
      final validCourses = courses.where((course) {
        return course['name'] != null && 
               course['startTime'] != null && 
               course['endTime'] != null;
      }).toList();
      
      print('有效课程数量: ${validCourses.length}');
      
      // 转换为 JSON 字符串
      final jsonStr = jsonEncode(validCourses);
      print('JSON 字符串长度: ${jsonStr.length}');
      
      // 写入文件
      final file = await _getLocalFile('course_table.json');
      await file.writeAsString(jsonStr);
      
      // 更新内存中的课程表
      _courseTable = validCourses.map((e) => CourseInfo.fromJson(e)).toList();
      print('课表数据保存完成');
    } catch (e, stackTrace) {
      print('保存课表数据失败: $e');
      print('错误堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 新增一门课程
  Future<void> addCourse(CourseInfo course) async {
    _courseTable.add(course);
    await saveCourseTable(_courseTable.map((e) => e.toJson()).toList());
  }

  /// 删除一门课程
  Future<void> removeCourse(CourseInfo course) async {
    _courseTable.remove(course);
    await saveCourseTable(_courseTable.map((e) => e.toJson()).toList());
  }

  /// 修改一门课程（通过索引或自定义主键）
  Future<void> updateCourse(int index, CourseInfo newCourse) async {
    if (index >= 0 && index < _courseTable.length) {
      _courseTable[index] = newCourse;
      await saveCourseTable(_courseTable.map((e) => e.toJson()).toList());
    }
  }

  /// 如果课表为空，插入模拟数据（仅调试用）
  Future<void> insertMockCoursesIfEmpty() async {
    if (_courseTable.isEmpty) {
      final now = DateTime.now();
      final mockCourses = [
        CourseInfo(
          name: '高等数学',
          startTime: DateTime(now.year, now.month, now.day, 8, 0),
          endTime: DateTime(now.year, now.month, now.day, 9, 40),
          location: '教一-101',
        ),
        CourseInfo(
          name: '大学英语',
          startTime: DateTime(now.year, now.month, now.day, 10, 0),
          endTime: DateTime(now.year, now.month, now.day, 11, 40),
          location: '教二-201',
        ),
        CourseInfo(
          name: '线性代数',
          startTime: DateTime(now.year, now.month, now.day, 14, 0),
          endTime: DateTime(now.year, now.month, now.day, 15, 40),
          location: '教三-301',
        ),
      ];
      await saveCourseTable(mockCourses.map((e) => e.toJson()).toList());
    }
  }

  /// 加载DDL
  Future<void> loadDDLList() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlFile');
    if (await file.exists()) {
      final jsonStr = await file.readAsString();
      final List<dynamic> jsonList = [];
      try{
        jsonList.addAll(json.decode(jsonStr));
      }catch(e){
        print('加载DDL数据失败: $e');
      }
      _ddlList = jsonList.map((e) => DDLItem.fromJson(e)).toList();
    } else {
      _ddlList = [];
      // 只在文件不存在时插入模拟数据
      await insertMockDdlsIfEmpty();
    }
  }

  /// 加载回收站DDL
  Future<void> loadDDLRecycle() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlRecycleFile');
    if (await file.exists()) {
      final jsonStr = await file.readAsString();
      final List<dynamic> jsonList = [];
      try{
        jsonList.addAll(json.decode(jsonStr));
      }catch(e){
        print('加载回收站DDL数据失败: $e');
      }
      _recycleBin = jsonList.map((e) => DDLItem.fromJson(e)).toList();
    } else {
      _recycleBin = [];
    }
  }

  /// 保存DDL列表到文件
  Future<void> saveDDLList(List<DDLItem> list) async {
    try {
      final file = await _getLocalFile('ddl_list.json');
      final jsonList = list.map((item) => item.toJson()).toList();
      print('保存DDL列表到文件: ${jsonList.length} 个项目');
      await file.writeAsString(jsonEncode(jsonList));
      print('DDL列表保存成功');
    } catch (e) {
      print('保存DDL列表失败: $e');
      rethrow;
    }
  }

  /// 保存回收站
  Future<void> saveDDLRecycle(List<DDLItem> ddls) async {
    _recycleBin = ddls;
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlRecycleFile');
    final jsonStr = json.encode(ddls.map((e) => e.toJson()).toList());
    await file.writeAsString(jsonStr);
  }

  /// 更新DDL
  Future<void> updateDDL(DDLItem ddl) async {
    print('开始更新DDL...');
    print('要更新的DDL: ${ddl.toJson()}');
    print('当前DDL列表: ${_ddlList.map((e) => e.toJson()).toList()}');
    
    // 使用pid进行匹配
    final index = _ddlList.indexWhere((item) => item.pid == ddl.pid);
    if (index != -1) {
      print('找到匹配的DDL，索引: $index');
      print('原DDL: ${_ddlList[index].toJson()}');
      _ddlList[index] = ddl;
      print('更新后的DDL: ${_ddlList[index].toJson()}');
    } else {
      print('未找到匹配的DDL，添加新DDL');
      _ddlList.add(ddl);
    }
    
    // 保存到文件
    await saveDDLList(_ddlList);
    print('DDL列表已保存到文件');
  }

  /// 新增DDL
  Future<void> addDDL(DDLItem ddl) async {
    // 检查是否已存在相同pid的DDL
    if (_ddlList.any((item) => item.pid == ddl.pid)) {
      print('发现重复的DDL，跳过添加');
      return;
    }
    _ddlList.add(ddl);
    await saveDDLList(_ddlList);
  }

  /// 如果DDL为空，插入模拟数据（仅调试用）
  Future<void> insertMockDdlsIfEmpty() async {
    // 只在文件不存在时插入模拟数据
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlFile');
    if (!await file.exists()) {
      final now = DateTime.now();
      final mockDdls = [
        DDLItem(
          title: '操作系统实验报告',
          deadline: now.add(const Duration(days: 2, hours: 3)),
          isUrgent: true,
        ),
        DDLItem(
          title: '线性代数作业',
          deadline: now.add(const Duration(days: 5)),
          isUrgent: false,
        ),
        DDLItem(
          title: '英语演讲PPT',
          deadline: now.add(const Duration(days: 1, hours: 5)),
          isUrgent: true,
        ),
        DDLItem(
          title: '创新创业计划书',
          deadline: now.add(const Duration(days: 10)),
          isUrgent: false,
        ),
      ];
      await saveDDLList(mockDdls);
    }
  }

  /// 从回收站删除单个DDL
  Future<void> removeSingleFromRecycleBin(DDLItem ddl) async {
    // 清理附件和图片
    await _cleanupAttachments(ddl.description);
    
    _recycleBin.remove(ddl);
    await saveDDLRecycle(_recycleBin);
  }

  /// 清理附件和图片
  Future<void> _cleanupAttachments(String? description) async {
    if (description == null || description.isEmpty) return;

    try {
      // 匹配图片和附件链接的正则表达式
      final imagePattern = RegExp(r'!\[.*?\]\((file://.*?)\)');
      final attachmentPattern = RegExp(r'\[.*?\]\((file://.*?)\)');

      // 获取所有匹配的文件路径
      final imageMatches = imagePattern.allMatches(description);
      final attachmentMatches = attachmentPattern.allMatches(description);

      // 合并所有文件路径
      final filePaths = <String>[];
      for (final match in imageMatches) {
        filePaths.add(match.group(1)!.replaceFirst('file://', ''));
      }
      for (final match in attachmentMatches) {
        filePaths.add(match.group(1)!.replaceFirst('file://', ''));
      }

      // 删除文件
      for (final path in filePaths) {
        try {
          final file = File(path);
          if (await file.exists()) {
            await file.delete();
            print('已删除文件: $path');
          }
        } catch (e) {
          print('删除文件失败: $path, 错误: $e');
        }
      }
    } catch (e) {
      print('清理附件失败: $e');
    }
  }

  /// 清空回收站
  Future<void> clearRecycleBin() async {
    // 清理所有 DDL 的附件和图片
    for (final ddl in _recycleBin) {
      await _cleanupAttachments(ddl.description);
    }
    
    _recycleBin = [];
    await saveDDLRecycle(_recycleBin);
  }

  /// 从回收站移除DDL
  Future<void> removeFromRecycleBin(DDLItem ddl) async {
    _recycleBin.removeWhere((item) => item.pid == ddl.pid);
    await saveDDLRecycle(_recycleBin);
  }

  /// 从DDL列表移除
  Future<void> removeFromDDL(DDLItem ddl) async {
    _ddlList.removeWhere((item) => item.pid == ddl.pid);
    await saveDDLList(_ddlList);
  }

  /// 添加到回收站
  Future<void> addToRecycleBin(DDLItem ddl) async {
    // 先检查是否已存在
    if (!_recycleBin.any((item) => item.pid == ddl.pid)) {
      _recycleBin.add(ddl);
      await saveDDLRecycle(_recycleBin);
    }
  }

  /// 加载DDL统计数据
  Future<void> _loadDDLStats() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlStatsFile');
    if (await file.exists()) {
      final jsonStr = await file.readAsString();
      final Map<String, dynamic> jsonMap ={};
      try{
        jsonMap.addAll(json.decode(jsonStr));
      }catch(e){
        print('加载DDL统计数据失败: $e');
      }
      _ddlStats = jsonMap.map((key, value) => MapEntry(
          key,
          Map<String, int>.from(value as Map<dynamic, dynamic>)));
    } else {
      _ddlStats = {};
    }
  }

  /// 保存DDL统计数据
  Future<void> _saveDDLStats() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_ddlStatsFile');
    final jsonStr = json.encode(_ddlStats);
    await file.writeAsString(jsonStr);
  }

  /// 更新DDL统计
  Future<void> updateDDLStats(String date, String type, [int delta = 1]) async {
    if (!_ddlStats.containsKey(date)) {
      _ddlStats[date] = {
        'completed': 0,
        'cancelled': 0,
        'abandoned': 0,
      };
    }
    _ddlStats[date]![type] = (_ddlStats[date]![type] ?? 0) + delta;
    if (_ddlStats[date]![type]! < 0) {
      _ddlStats[date]![type] = 0;
    }
    await _saveDDLStats();
    // 同时更新小目标数据
    await updateGoalStats(date, type, delta);
  }

  /// 获取DDL统计
  Map<String, Map<String, int>> get ddlStats => _ddlStats;

  /// 加载小目标数据
  Future<void> _loadGoalStats() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_goalStatsFile');
    final Map<String, Map<String, int>> fixedMap = {};
    final Map<String, dynamic> jsonMap = {};
    
    // 获取当前年份的所有日期
    final currentYear = DateTime.now().year;
    final first = DateTime(currentYear, 1, 1);
    final last = DateTime(currentYear, 12, 31);
    
    // 为所有日期初始化默认值
    for (int i = 0; i <= last.difference(first).inDays; i++) {
      final d = first.add(Duration(days: i));
      final date = '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
      fixedMap[date] = {
        'completed': 0,
        'cancelled': 0,
        'abandoned': 0,
      };
    }
    
    if (await file.exists()) {
      final jsonStr = await file.readAsString();
      try {
        jsonMap.addAll(json.decode(jsonStr));
      } catch(e) {
        print('加载小目标数据失败: $e');
      }
      jsonMap.forEach((key, value) {
        final parts = key.split('-');
        if (parts.length == 3) {
          final fixedKey = '${parts[0]}-${parts[1].padLeft(2, '0')}-${parts[2].padLeft(2, '0')}';
          // 合并同一天的不同格式
          if (fixedMap.containsKey(fixedKey)) {
            // 合并数值
            value.forEach((k, v) {
              fixedMap[fixedKey]![k] = (fixedMap[fixedKey]![k] ?? 0) + (v as int);
            });
          }
        }
      });
    }
    
    _goalStats = fixedMap;
    print('加载小目标数据：$_goalStats');
    
    // 特别输出5月4号的数据
    final may4th = '${currentYear}-05-04';
    print('5月4号的数据：${_goalStats[may4th]}');
    
    await _saveGoalStats(); // 保存更新后的数据
  }

  /// 保存小目标数据
  Future<void> _saveGoalStats() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_goalStatsFile');
    final jsonStr = json.encode(_goalStats);
    await file.writeAsString(jsonStr);
    print('小目标数据已保存到文件');
  }

  /// 更新小目标数据
  Future<void> updateGoalStats(String date, String type, [int delta = 1]) async {
    // 统一 key 格式
    final parts = date.split('-');
    final fixedDate = '${parts[0]}-${parts[1].padLeft(2, '0')}-${parts[2].padLeft(2, '0')}';
    print('更新小目标数据：date=$fixedDate, type=$type, delta=$delta');
    if (!_goalStats.containsKey(fixedDate)) {
      _goalStats[fixedDate] = {
        'completed': 0,
        'cancelled': 0,
        'abandoned': 0,
      };
    }
    _goalStats[fixedDate]![type] = (_goalStats[fixedDate]![type] ?? 0) + delta;
    if (_goalStats[fixedDate]![type]! < 0) {
      _goalStats[fixedDate]![type] = 0;
    }
    print('更新后的小目标数据：$_goalStats');
    await _saveGoalStats();
    // 更新自律值：完成+1，取消和放弃都-1
    int score = 0;
    if (type == 'completed') score += delta;
    if (type == 'cancelled' || type == 'abandoned') score -= delta;
    final oldScore = getDisciplineScore(fixedDate);
    await setDisciplineScore(fixedDate, oldScore + score);
  }

  /// 获取小目标数据
  Map<String, Map<String, int>> get goalStats => _goalStats;

  /// 加载自律值数据
  Future<void> _loadDisciplineScores() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_disciplineScoresFile');
    if (await file.exists()) {
      final jsonStr = await file.readAsString();

      final Map<String, dynamic> jsonMap ={};
      try{
        jsonMap.addAll(json.decode(jsonStr));
      }catch(e){
        print('加载自律值数据失败: $e');
      }    
      _disciplineScores = jsonMap.map((year, value) => MapEntry(
        year,
        Map<String, int>.from(value as Map),
      ));
    } else {
      _disciplineScores = {};
    }
  }

  Future<void> _saveDisciplineScores() async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$_disciplineScoresFile');
    final jsonStr = json.encode(_disciplineScores);
    await file.writeAsString(jsonStr);
  }

  int getDisciplineScore(String date) {
    final year = date.split('-')[0];
    return _disciplineScores[year]?[date] ?? 0;
  }

  Future<void> setDisciplineScore(String date, int score) async {
    final year = date.split('-')[0];
    _disciplineScores[year] ??= {};
    _disciplineScores[year]![date] = score;
    await _saveDisciplineScores();
  }

  Future<File> _getLocalFile(String fileName) async {
    final dir = await getApplicationDocumentsDirectory();
    return File('${dir.path}/$fileName');
  }

  List<CourseInfo> getCourseTable(){
    return courseTable;
  }

  List<DDLItem> getDDLList(){
    return ddlList;
  }


  List<Map<String, dynamic>> getTodayCourses() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    print('获取今日课表...');
    print('今天日期: $today');
    
    final allCourses = _courseTable;
    print('所有课程数量: ${allCourses.length}');
    
    final todayCourses = allCourses.where((course) {
      final startTime = course.startTime;
      if (startTime == null) return false;
      
      // 直接比较年月日
      return startTime.year == today.year &&
             startTime.month == today.month &&
             startTime.day == today.day;
    }).map((course) => course.toJson()).toList();
    
    // 按开始时间升序排序
    todayCourses.sort((a, b) {
      final aTime = DateTime.parse(a['startTime']);
      final bTime = DateTime.parse(b['startTime']);
      return aTime.compareTo(bTime);
    });
    
    print('今日课程数量: ${todayCourses.length}');
    print('今日课程详情:');
    for (var course in todayCourses) {
      print('课程卡片信息:');
      print('  课程名称: ${course['name']}');
      print('  开始时间: ${course['startTime']}');
      print('  结束时间: ${course['endTime']}');
      print('  上课地点: ${course['location']}');
      print('  --------------------');
    }
    
    return todayCourses;
  }

  DateTime? _parseDateTime(String? dateTimeStr) {
    if (dateTimeStr == null || dateTimeStr.isEmpty) return null;
    
    try {
      // 尝试解析格式：20240301T080000
      if (dateTimeStr.length >= 15) {
        final year = int.parse(dateTimeStr.substring(0, 4));
        final month = int.parse(dateTimeStr.substring(4, 6));
        final day = int.parse(dateTimeStr.substring(6, 8));
        final hour = int.parse(dateTimeStr.substring(9, 11));
        final minute = int.parse(dateTimeStr.substring(11, 13));
        return DateTime(year, month, day, hour, minute);
      }
    } catch (e) {
      print('解析日期时间失败: $dateTimeStr, 错误: $e');
    }
    return null;
  }

  /// 导出所有应用数据
  Future<Map<String, dynamic>> exportAllData() async {
    final Map<String, dynamic> exportData = {
      'courseTable': _courseTable.map((e) => e.toJson()).toList(),
      'ddlList': _ddlList.map((e) => e.toJson()).toList(),
      'recycleBin': _recycleBin.map((e) => e.toJson()).toList(),
      'ddlStats': _ddlStats,
      'goalStats': _goalStats,
      'disciplineScores': _disciplineScores,
    };
    return exportData;
  }

  /// 导入所有应用数据
  Future<void> importAllData(Map<String, dynamic> importData) async {
    try {
      // 导入课表数据
      if (importData.containsKey('courseTable')) {
        _courseTable = List<Map<String, dynamic>>.from(importData['courseTable'])
            .map((e) => CourseInfo.fromJson(e))
            .toList();
        await saveCourseTable(_courseTable.map((e) => e.toJson()).toList());
      }

      // 导入DDL数据
      if (importData.containsKey('ddlList')) {
        _ddlList = List<Map<String, dynamic>>.from(importData['ddlList'])
            .map((e) => DDLItem.fromJson(e))
            .toList();
        await saveDDLList(_ddlList);
      }

      // 导入回收站数据
      if (importData.containsKey('recycleBin')) {
        _recycleBin = List<Map<String, dynamic>>.from(importData['recycleBin'])
            .map((e) => DDLItem.fromJson(e))
            .toList();
        await saveDDLRecycle(_recycleBin);
      }

      // 导入DDL统计数据
      if (importData.containsKey('ddlStats')) {
        final ddlStatsData = importData['ddlStats'] as Map<String, dynamic>;
        _ddlStats = ddlStatsData.map((key, value) {
          final stats = value as Map<String, dynamic>;
          return MapEntry(key, {
            'completed': stats['completed'] as int? ?? 0,
            'cancelled': stats['cancelled'] as int? ?? 0,
            'abandoned': stats['abandoned'] as int? ?? 0,
          });
        });
        await _saveDDLStats();
      }

      // 导入小目标数据
      if (importData.containsKey('goalStats')) {
        final goalStatsData = importData['goalStats'] as Map<String, dynamic>;
        _goalStats = goalStatsData.map((key, value) {
          final stats = value as Map<String, dynamic>;
          return MapEntry(key, {
            'completed': stats['completed'] as int? ?? 0,
            'cancelled': stats['cancelled'] as int? ?? 0,
            'abandoned': stats['abandoned'] as int? ?? 0,
          });
        });
        await _saveGoalStats();
      }

      // 导入自律值数据
      if (importData.containsKey('disciplineScores')) {
        final disciplineScoresData = importData['disciplineScores'] as Map<String, dynamic>;
        _disciplineScores = disciplineScoresData.map((year, value) {
          final scores = value as Map<String, dynamic>;
          return MapEntry(year, scores.map((date, score) => 
            MapEntry(date, score as int? ?? 0)
          ));
        });
        await _saveDisciplineScores();
      }

      print('数据导入成功');
    } catch (e, stackTrace) {
      print('数据导入失败: $e');
      print('错误堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 添加到DDL列表
  Future<void> addToDDL(DDLItem ddl) async {
    // 检查是否已存在相同pid的DDL
    if (!_ddlList.any((item) => item.pid == ddl.pid)) {
      _ddlList.add(ddl);
      await saveDDLList(_ddlList);
    }
  }

  /// 从回收站恢复DDL
  Future<void> restoreFromRecycle(DDLItem item) async {
    // 从回收站移除
    _recycleBin.removeWhere((i) => i.pid == item.pid);
    await saveDDLRecycle(_recycleBin);
    
    // 添加到活动列表
    if (!_ddlList.any((i) => i.pid == item.pid)) {
      _ddlList.add(item);
      await saveDDLList(_ddlList);
    }
  }
}
